package com.lvtongka.app.http

import android.text.TextUtils
import com.google.gson.Gson
import com.lvtongka.app.base.BaseApplication
import com.lvtongka.app.common.AppUtils
import com.lvtongka.app.common.bean.BaseResp
import com.lvtongka.app.helper.LJHelper
import com.lvtongka.app.helper.SPHelper
import okhttp3.*
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okio.IOException
import java.util.concurrent.TimeUnit

class OkhttpUtils {
    companion object {
        private var instance: OkhttpUtils? = null
        private var okhttp: OkHttpClient? = null

        @JvmStatic
        @Synchronized
        fun getInstance(): OkhttpUtils {
            if (instance == null) instance = OkhttpUtils()
            okhttp = OkHttpClient().newBuilder()
                .retryOnConnectionFailure(true)
                .connectTimeout(10000, TimeUnit.SECONDS) //连接超时
                .readTimeout(10000, TimeUnit.SECONDS) //读取超时
                .writeTimeout(10000, TimeUnit.SECONDS) //写超时
                .build()
            return instance!!
        }
    }

    /**
     * Post请求
     * @json 请求参数
     * @url 请求地址
     * @httpCallBack 回调
     */
    fun postRequest(json: String, url: String, httpCallBak: HttpCallBack, accessToken: String? = "") {
        if (!AppUtils.isNetworkAvailable()) {
            httpCallBak.onError("网络不可用，请检查网络连接")
            return
        }
        val requestBody =
            RequestBody.create("application/json; charset=utf-8".toMediaTypeOrNull(), json)

        var request: Request = Request.Builder().url(url)
            .post(requestBody)
            .build()

        if (!TextUtils.isEmpty(accessToken)) {
            request = Request.Builder().url(url).addHeader("Authorization", accessToken!!)
            .post(requestBody)
                .build()
        }

        val call: Call? = okhttp?.newCall(request)
        call?.enqueue(object : Callback {
            override fun onFailure(call: Call, e: IOException) {
                httpCallBak.onError(e.printStackTrace().toString())
            }

            override fun onResponse(call: Call, response: Response) {
                if (response.isSuccessful) {
                    response.body?.let {
                        val content = it.string()
                        val resp : BaseResp = Gson().fromJson(content, BaseResp::class.java)
                        if (resp.code == 0 || resp.code == 200) {
                            httpCallBak.onSuccess(content)
                        } else {
                            httpCallBak.onError(resp.msg)
                        }
                    }
                } else {
                    if (response.code == 401) {
                        // token失效
                        if (LJHelper.isLogin()) {
                            SPHelper.clearLoginInfo()
                            BaseApplication.jumpLogin()
                        } else {
                            httpCallBak.onError(response.message)
                        }
                    } else {
                        httpCallBak.onError(response.message)
                    }
                }
            }
        })
    }
}